package com.fs.user.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",value = "/*")
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //对哪些请求直接放行  login.jsp   LoginServlet  register.jsp   index.jsp
        String uri = request.getRequestURI();
        if(!uri.contains("pages")  ||  uri.equals("/LoginServlet") ||  uri.equals("/UploadServlet")){
            chain.doFilter(req, resp);
            return;
        }
        if(request.getSession().getAttribute("login") == null){ //没有登录
            //跳转到登录页面
            response.sendRedirect("/login.jsp");
            return;
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
